﻿using System;
using System.Collections.Generic;
using System.Linq;
using CID.Domain.Exceptions;
using NailsFramework.Persistence;

namespace CID.Domain.Infrastructure
{
    public class TemplateType : Model<TemplateType>, ITemplateType
    {
        public virtual int Id { get; private set; }
        public virtual string Name { get; set; }
        public virtual string Description { get; set; }
        public virtual bool Enabled { get; set; }
        public virtual string TemplateContentEditorConverterType { get; set; }
        public virtual string TemplateContentEditorViewName { get; set; }

        private IList<ITemplate> templates = new List<ITemplate>();
        public virtual IEnumerable<ITemplate> Templates { get { return templates; } }

        protected TemplateType()
        {
            Enabled = true;
        }

        public TemplateType(string name, string description, string templateContentEditorConverterType, string templateContentEditorViewName) : this()
        {
            Name = name;
            Description = description;
            TemplateContentEditorConverterType = templateContentEditorConverterType;
            TemplateContentEditorViewName = templateContentEditorViewName;
        }

        public virtual IActivationTemplate CreateActivationTemplate(string name, string description, byte[] content)
        {
            var result = new ActivationTemplate(this, name, description, content);
            AddTemplate(result);
            return result;
        }

        public virtual IDeactivationTemplate CreateDeactivationTemplate(string name, string description, byte[] content)
        {
            var result = new DeactivationTemplate(this, name, description, content);
            AddTemplate(result);
            return result;
        }

        public virtual IDeploymentTemplate CreateDeploymentTemplate(string name, string description, byte[] content)
        {
            var result = new DeploymentTemplate(this, name, description, content);
            AddTemplate(result);
            return result;
        }

        //TODO: this method should be removed or moved to private. This needs to change some tests
        public virtual void AddTemplate(ITemplate template)
        {
            if (Equals(template.Type))
            {
                if (templates.Count(x => x.Name.Equals(template.Name, StringComparison.InvariantCultureIgnoreCase)) > 0)
                    throw new DuplicateChildException(this, template);
                templates.Add(template);
            }
        }

        //TODO: this method should be removed or moved to private. This needs to change some tests
        public virtual void RemoveTemplate(ITemplate template)
        {
            if (templates.Contains(template))
            {
                templates.Remove(template);
            }
        }
    }
}
